using System;
using System.Web;
using System.Web.Mvc;
using Orchard.DisplayManagement;
using Orchard.DisplayManagement.Descriptors;
using Orchard.Localization;
using Orchard.Mvc.Html;
using So.ImageResizer.Services;
using Orchard.Environment.Extensions;

namespace So.ImageResizer {
    [OrchardFeature("So.ImageResizer.Automatically")]
    public class Shapes : IShapeTableProvider {
        private readonly IImageResizerService _imageResizerService;

        public Shapes(IImageResizerService imageResizerService) {
            _imageResizerService = imageResizerService;
            T = NullLocalizer.Instance;
        }

        public Localizer T { get; set; }

        public void Discover(ShapeTableBuilder builder) {
            builder.Describe("Content").OnDisplayed(context => {
                                                        var html = context.ShapeMetadata.ChildContent.ToString();
                                                        context.ShapeMetadata.ChildContent = new HtmlString(_imageResizerService.UpdateAllImageSourcesToResizedUrlsFromHtml(html));
                                                    });
            builder.Describe("Widget").OnDisplayed(context => {
                                                       var html = context.ShapeMetadata.ChildContent.ToString();
                                                       context.ShapeMetadata.ChildContent = new HtmlString(_imageResizerService.UpdateAllImageSourcesToResizedUrlsFromHtml(html));
                                                   });
        }
    }
}